<template>
  <div ref="terminal"></div>
</template>

<script>
import { Terminal } from 'xterm'
import { FitAddon } from 'xterm-addon-fit'
import "xterm/css/xterm.css"
import api from "@/api/controller";

export default {
  name: "SshTerminal",
  props: {
    sshConfig: Object
  },
  data: function () {
    return {
      term: "",
      socket: "",
    }
  },
  mounted: function () {
    setTimeout(this.init, 100);
  },
  methods: {
    init: function () {
      this.createWsConnect();
      this.createSshConnect();
      this.rendererTerminal();
    },
    logicalControl: function () {
      let me = this;
      this.socket.onmessage = function(event) {
        console.log("websocket message: " + event.timeStamp + " - " + event.data)
        me.term.write(event.data)
      }
      this.socket.onclose = function(event) {
        const tipStr = "⏰·会话超时已断开";
        me.term.writeln('')
        me.term.write(tipStr)
        console.log("close websocket: " + event.timeStamp)
      }
      this.socket.onopen = function (event) {
        me.term.writeln('Welcome to web terminal by SundayLi make!')
        // 发送一次回车得到控制台回显
        me.socket.send("\r");
        console.log("open websocket: " + event.timeStamp)
      }
      // 监听用户输入
      this.term.onData(key => {
        console.log("用户输入: " + key)
        me.socket.send(key);
      })
    },
    createSshConnect: function () {
      let me = this;
      let request = {
        user: me.sshConfig.user,
        host: me.sshConfig.host,
        password: me.sshConfig.password,
        businessId: me.sshConfig.businessId,
        port: 22,
        rows: 100,
        cols: 200,
        width: 100 * 8,
        height: 200 * 8
      }
      api.sshController.openSshTerminal(request).then(function (res) {
        console.log(res);
        me.logicalControl();
      });
    },
    createWsConnect: function () {
      const socket = new WebSocket("ws://" + location.hostname + ":" + location.port + "/api/ws?businessId=" + this.sshConfig.businessId);
      socket.onerror = function(event) {
        alert("websocket 连接异常!")
        console.log("websocket error: " + event.timeStamp);
      };
      this.socket = socket;
    },
    rendererTerminal: function () {
      // 初始化控制台
      let term = new Terminal({
        rendererType: "canvas", //渲染类型
        rows: 100,
        cols: 200,
        convertEol: true, //启用时，光标将设置为下一行的开头
        disableStdin: false, //是否应禁用输入
        cursorBlink: true, //光标闪烁
        theme: {
          foreground: "#ECECEC", //字体
          background: "#000000", //背景色
          cursor: "help", //设置光标
          lineHeight: 20
        }
      });
      const fitAddon = new FitAddon();
      term.loadAddon(fitAddon);
      fitAddon.fit();
      term.open(this.$refs.terminal);
      this.term = term;
    }
  }
}
</script>

<style scoped>

</style>